#include<vector>
#include "offlinemessagemodel.h"
#include "mysql.h"
using namespace ChatRoom;

MySQL mysql;
bool OfflineMsgModel::insert_offline(int userid, std::string& message)
{
    char sql[1024] = {0};
    sprintf(sql, "insert into offlinemessage(userid, message) values(%d, '%s')", userid, message.c_str());
    MySQL mysql;
    if (mysql.Connect())
    {
        return mysql.Update(sql);
    }
    return false;
}

bool OfflineMsgModel::del_user(int userid)
{
    char sql[1024] = {0};
    sprintf(sql, "delete from offlinemessage where userid = %d", userid);
    MySQL mysql;
    if (mysql.Connect())
    {
        return mysql.Update(sql);
    }
    return false;
}

// 根据用户号码查询用户信息
vector<OfflineMsgModel> OfflineMsgModel::query(int id)
{
    // 1.组装sql语句
    char sql[1024] = {0};
    if (id != 0) {
        std::snprintf(sql, sizeof(sql), "select * from offlinemessage where userid = %d", id);
    } else {
        std::snprintf(sql, sizeof(sql), "select * from offlinemessage");
    }

    std::vector<OfflineMsgModel> vec;

    // 复用全局的 mysql 对象
    if (mysql.Connect())
    {
        MYSQL_RES *res = mysql.Query(sql);
        if (res != nullptr)
        {
            MYSQL_ROW row;
            while ((row = mysql_fetch_row(res)) != nullptr)
            {
                // 假设 OfflineMsgModel 有对应的构造函数
                OfflineMsgModel msg(atoi(row[0]), std::string(row[1]));
                vec.push_back(msg);
            }
            mysql_free_result(res);
        }
    }

    return vec;
}



//统计个数
int OfflineMsgModel::count_oddline_message(int userid)
{
    char sql[1024] = {0};
    sprintf(sql,"select count(*) from offlinemessage where userid = %d",userid);
    int count = 0;
    MySQL mysql;
    if(mysql.Connect())
    {
        MYSQL_RES*res = mysql.Query(sql);
        if(res != nullptr)
        {
            MYSQL_ROW row = mysql_fetch_row(res);
            if(row != nullptr)
            {
                count = atoi(row[0]);
            }
            mysql_free_result(res);
        }
    }
    return count;
}


